package com.denlaku.longan.filter;

import com.denlaku.longan.Const;
import com.denlaku.longan.core.HttpSessionManager;
import com.denlaku.longan.vo.User;
import jakarta.servlet.FilterChain;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.http.HttpStatus;

import java.util.Optional;

/**
 * @author tianx
 */
public class LogoutFilter extends HttpFilter {
    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) {
        HttpSession httpSession = request.getSession(false);
        if (httpSession != null) {
            Long userId = getUserId(httpSession);
            HttpSessionManager.removeSession(userId);
            httpSession.invalidate();
        }
        response.setStatus(HttpStatus.OK.value());
    }

    private Long getUserId(HttpSession httpSession) {
        Object userInfo = httpSession.getAttribute(Const.KEY_USER_INFO);
        return Optional.ofNullable(userInfo)
                .filter(value -> value instanceof User)
                .map(value -> (User) value)
                .map(User::getId)
                .orElse(null);
    }
}
